﻿using System;
using System.Collections;
using System.Windows.Forms;
using B12_Ex01_Guy_066473471_Erez_021616735.FacebookApplicationLogic;
using B12_Ex01_Guy_066473471_Erez_021616735.userInterfaceForWindowsInWinForm;
using FacebookWrapper;
using FacebookWrapper.ObjectModel;
using System.Threading;
using System.Collections.Generic;
using System.Drawing;

namespace B12_Ex01_Guy_066473471_Erez_021616735
{ 
    public partial class FormMain : Form
    {
        //private FacebookApplication m_FBApp = null;
        private FacebookApplication2 m_FBApp = null;
        private AppSetting m_setting = null;
        
        public FormMain()
        {
            InitializeComponent();
            m_FBApp = FacebookApplication2.Instance;
            //Clipboard.SetText("vodka12345");
            Clipboard.SetText("designpatterns");
        }

        /// <summary>
        /// Checks prior wheelbarrow settings
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                m_setting = AppSetting.loadFromFile();
                if (m_setting.AutoLogIn == true)
                {
                    checkBoxRememberMe.Checked = true;
                    Connect();
                    buttonExitAndLogOut.Visible = true;
                    MakeButtenEnable();
                }
            }
            catch
            {
                //if (m_FBApp2.LooIn() == true)
                //{
                //    checkBoxRememberMe.Visible = false;
                //    buttonExitAndLogOut.Visible = true;
                //    fetchUserInfo();
                //    MakeButtenEnable();
                //}
                //else 
                //{
                //    MessageBox.Show("The application cannot connect to FaceBook, please try again");
                //    this.Close();
                //}
            }
        }


        private void MakeButtenEnable()
        {
            buttonFriends.Enabled = true;
            buttonFriendsMale.Enabled = true;
            buttonFriendsFemale.Enabled = true;
            buttonUnFriends.Enabled = true;
        }

        /// <summary>
        /// Saving settings the next run
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            
            if (m_FBApp != null)
            {
                m_setting = AppSetting.Instance;
                m_setting.AutoLogIn = checkBoxRememberMe.Checked;
                m_setting.AccessToken = m_FBApp.AccessToken;
                m_setting.UserName = m_FBApp.LoggedInUser.Name;
                try
                {
                    m_setting.SaveToFile();
                }
                catch
                {
                    MessageBox.Show("Your data could not be saved!");
                }
           }
        }

        /// <summary>
        /// Facebook Connect operation by keeping the AccessToken(Auto logIn)
        /// </summary>
        private void Connect()
        {
            if (m_FBApp.Connect(m_setting.AccessToken) == true)
            {
                buttonLogIn.Text = "Exit";
                checkBoxRememberMe.Visible = false;
                fetchUserInfo();
            }
            else
            {
                LooIn();
            }
            //LoginResult result = FacebookService.Connect(m_setting.AccessToken);

            //if (string.IsNullOrEmpty(result.ErrorMessage) && result.LoggedInUser != null)
            //{
            //    m_FBApp = new FacebookApplication(result.LoggedInUser) { AccessToken = result.AccessToken};
            //    buttonLogIn.Text = "Exit";
            //    checkBoxRememberMe.Visible = false;
            //    fetchUserInfo();
            //}
            //else
            //{
            //    MessageBox.Show(result.ErrorMessage);
            //}
        }
        
        private void LooIn()
        {
            if (m_FBApp.LooIn() == true)
            {
                checkBoxRememberMe.Visible = false;
                buttonExitAndLogOut.Visible = true;
                fetchUserInfo();
                MakeButtenEnable();
            }
            else
            {
                MessageBox.Show("The application cannot connect to FaceBook, please try again");
                this.Close();
            }                     
        }

        private void fetchUserInfo()
        {
            pictureBoxUser.LoadAsync(m_FBApp.LoggedInUser.PictureSmallURL);
            LabelUserName.Text = m_FBApp.LoggedInUser.Name;                
        }

        private void buttonLogIn_Click(object sender, EventArgs e)
        {
            if (m_FBApp.LoggedInUser == null)
            {
                LooIn();
                buttonLogIn.Text = "EXIT";
            }
            else
            {
                this.Close();
            }
        }

     
      
        
        //butten friends
        private void buttonFriends_Click(object sender, EventArgs e)
        {
            var Friends = m_FBApp.getFriends();

            populatingListBoxFriends(Friends);
        }
        
        private void buttonFriendsMale_Click(object sender, EventArgs e)
        {
            var Friends = m_FBApp.getMaleFriends();

            populatingListBoxFriends(Friends);
        }

        private void buttonFriendsFemale_Click(object sender, EventArgs e)
        {
            var Friends = m_FBApp.getFemaleFriends();
            
            populatingListBoxFriends(Friends);
        }

        private void buttonExFriend_Click(object sender, EventArgs e)
        {
            var ExFriends = m_FBApp.getExFriendsNames();
            
            populatingListBoxFriends(ExFriends);

            pictureBoxFriend.Image = null;
        }
       
        private void populatingListBoxFriends(ICollection i_Collection)
        {
            OrganizeAreaFriend();
            
            listBoxInfo.Items.Clear();

            labelType.Text = "Number Friends: ";
            labelInfo.Text = i_Collection.Count.ToString();

            if (i_Collection.Count == 0)
            {
                listBoxInfo.Items.Add("No data");
            }
            else foreach (var curr in i_Collection)
            {
               // listBoxInfo.Items.Add(new userAdpter() { user = curr as User });
                listBoxInfo.Items.Add(curr);
            }
           
        }

        private void listBoxFriends_SelectedIndexChanged(object sender, EventArgs e)
        {
            listBoxFrindInfoReset();

            if (listBoxInfo.SelectedItems.Count == 1)
            {
                User selectedFriend = listBoxInfo.SelectedItem as User;
                if (selectedFriend != null)
                {
                    buttonEvent.Enabled = true;
                    buttonCheckins.Enabled = true;
                    buttonStatus.Enabled = true;
                    buttonAlbums.Enabled = true;
                    labelBirthdayInfo.Text = "";
                    labelCity.Text = "";

                    if (selectedFriend.PictureLargeURL != null)
                    {
                        pictureBoxFriend.LoadAsync(selectedFriend.PictureLargeURL);
                    }
                    else
                    {
                        pictureBoxUser.Image = pictureBoxUser.ErrorImage;
                    }

                    String str = selectedFriend.Birthday;
                    if (str != null)
                    {
                        labelBirthday.Visible = true;
                        labelBirthdayInfo.Text = selectedFriend.Birthday.ToString();
                    }

                    try
                    {
                        var curr = selectedFriend.Location;
    
                        if (curr != null)
                        {
                            labellivesIn.Visible = true;
                            labelCity.Text = curr.Name;
                        }
                    }
                    catch (System.Exception ex)
                    { 
                        ///Do nothing
                    }
                            
                }
            }

        }
        
        ///butten info about friend
        private void buttonEvent_Click(object sender, EventArgs e)
        {
            User selectedFriend = listBoxInfo.SelectedItem as User;

            if (selectedFriend != null)
            {
                populatingListBoxFriendInfo(selectedFriend.Events);
            } 
        }

        private void buttonCheckins_Click(object sender, EventArgs e)
        {
            User selectedFriend = listBoxInfo.SelectedItem as User;
            if (selectedFriend != null)
            {
                populatingListBoxFriendInfo(selectedFriend.Checkins);
            }

        }

        private void buttonStatus_Click(object sender, EventArgs e)
        {
            User selectedFriend = listBoxInfo.SelectedItem as User;

            if (selectedFriend != null)
            {         
                populatingListBoxFriendInfo(selectedFriend.Statuses);
            }
        }

        private void buttonAlbums_Click(object sender, EventArgs e)
        {
            User selectedFriend = listBoxInfo.SelectedItem as User;

            if (selectedFriend != null)
            {
                populatingListBoxFriendInfo(selectedFriend.Albums);
            }
        }

    
        /// <summary>
        /// populating ListBoxFriendInfo in Checkins/Checkins/Events.....
        /// </summary>
        /// <param name="i_Collection">Must be a collection that you can do it "foreach"</param>
        private void populatingListBoxFriendInfo(ICollection i_Collection)
        {
            listBoxFrindInfoReset();
            
            if (i_Collection.Count == 0)
            {
                listBoxFriendInfo.Items.Add("No data");
            }
            else foreach (var friend in i_Collection)
            {
                IPostedItem currItem = FactoryAdapterPostItem.AdapterPostedItem.CreateAdapterPostItem(friend as PostedItem);
                if (currItem != null)
                {
                    listBoxFriendInfo.Items.Add(currItem);
                }
                else 
                {
                    listBoxFriendInfo.Items.Add(friend);
                }                                       
            }
        }
        
        
        private void listBoxFrindInfo_SelectedIndexChanged(object sender, EventArgs e)
        {            
            if (listBoxFriendInfo.SelectedItems.Count == 1)
            {
                var selectedItem = listBoxFriendInfo.SelectedItem as Event;

                if (selectedItem != null)
                {
                    if (selectedItem.PictureNormalURL != null)
                    {
                        pictureBoxFrinedInfo.LoadAsync(selectedItem.PictureNormalURL);
                    }
                    else
                    {
                        pictureBoxFrinedInfo.Image = pictureBoxUser.ErrorImage;
                    }
                }

                var selsect = listBoxFriendInfo.SelectedItem as Album;
                if (selsect != null)
                {
                    flowLayoutPanel1.Controls.Clear();
                    pictureBoxFrinedInfo.LoadAsync(selsect.CoverPhotoThumbURL);         
                    foreach(Photo curr in selsect.Photos)
                    {
                        //PictureBoxLazy pictureBox = new PictureBoxLazy();
                        PictureFaceBookBox pictureBox = new PictureFaceBookBox(curr);
                        pictureBox.ImageLocation = curr.ThumbURL;
                        //pictureBox.Size = new System.Drawing.Size(180,150);
                        pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
                        this.flowLayoutPanel1.Controls.Add(pictureBox);
                    }
                }
            }          
        }

        private void listBoxFrindInfoReset()
        {
            listBoxFriendInfo.Items.Clear();
            flowLayoutPanel1.Controls.Clear();
            pictureBoxFrinedInfo.Image = null;
        }

        private void OrganizeAreaFriend()
        {
            listBoxFrindInfoReset();

            labelBirthdayInfo.Text = "";
            labelCity.Text = "";
            pictureBoxFriend.Image = null;
            buttonEvent.Enabled = false;
            buttonCheckins.Enabled = false;
            buttonStatus.Enabled = false;
            buttonEvent.Enabled = false;
            labellivesIn.Visible = false;
            labelBirthday.Visible = false;
        }

        /// <summary>
        /// In the current API cannot be 
        /// LogOut so there is button cancel automatic entry
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonExitAndLogOut_Click(object sender, EventArgs e)
        {
            checkBoxRememberMe.Checked = false;
            this.Close();
        }

        private void pictureFaceBookBox1_Paint(object sender, PaintEventArgs e)
        {

        }

        

      

       

    }

   
    public class userAdpter : User
    {
        public User user { get; set; }

        public override string ToString()
        {
            return user.Name ;
        }
    }
}
